package com.study.talk.ui.app.launcher

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.study.talk.R
import com.study.talk.utils.extras.start

class PermissionActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "PermissionActivity"
    }

    private val dialog: AlertDialog by lazy {
        AlertDialog.Builder(this@PermissionActivity).setTitle("提醒")
            .setMessage("拒绝授予权限将无法使用此应用哦！你确定退出嘛？")
            .setNegativeButton("确定") { _, _ -> finish() }.setPositiveButton("去授权") { _, _ ->
                simpleSetting()
            }.create()
    }
    private val permissionLauncher: ActivityResultLauncher<Array<String>> =
        registerForActivityResult(
            ActivityResultContracts.RequestMultiplePermissions()
        ) { result: Map<String, Boolean> ->
            if (result.isEmpty()) return@registerForActivityResult
            val hasDeny = result.entries.any { !it.value }
            if (hasDeny) showDialog()
            else otherPermissions()
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_permission)
        checkPermission()
    }

    private fun toStart() {
        start(StartActivity::class.java)
        finish()
    }

    private fun showDialog() {
        if (!dialog.isShowing) {
            dialog.show()
            dialog.setCanceledOnTouchOutside(false)
        }
    }

    private fun checkPermission() {
        val permissions =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                arrayOf(
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.READ_MEDIA_IMAGES,
                    Manifest.permission.READ_MEDIA_AUDIO,
                    Manifest.permission.READ_MEDIA_VIDEO,
                    Manifest.permission.POST_NOTIFICATIONS,
                    Manifest.permission.FOREGROUND_SERVICE_REMOTE_MESSAGING
                )
            } else {
                arrayOf(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                )
            }
        val hasDeny = permissions.any {
            val result = ActivityCompat.checkSelfPermission(
                this@PermissionActivity, it
            ) != PackageManager.PERMISSION_GRANTED
            if (result) Log.e(TAG, "checkPermission: $it")
            result
        }
        if (hasDeny) permissionLauncher.launch(permissions)
        else otherPermissions()
    }

    override fun onResume() {
        super.onResume()
        if (!dialog.isShowing) {
            checkPermission()
        }
    }

    private fun otherPermissions() {
        if (!Settings.canDrawOverlays(this@PermissionActivity)) {  //获取悬浮窗
            showDialogForStartActivityPermission(
                Intent(
                    Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse(
                        "package:$packageName"
                    )
                ).apply {
                    setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }, "应用需要获取悬浮窗权限"
            )
            return
        }
        toStart()
    }

    // 跳转至设置页面，让用户手动开启允许管理所有文件
    fun setting() {
        if (!Environment.isExternalStorageManager()) {
            startActivity(Intent(
                Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
                Uri.parse("package:$packageName")
            ).apply { setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) })
        }
    }

    // 跳转系统设置-悬浮窗页面
    fun alertWindowsPermission() {
        val intent = Intent(
            Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse(
                "package:$packageName"
            )
        )
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(intent)
    }

    private fun simpleSetting() {
        try {// 将用户引导到系统设置页面
            startActivity(Intent("android.settings.APPLICATION_DETAILS_SETTINGS").apply {
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                setData(Uri.fromParts("package", packageName, null))
            })
        } catch (e: Exception) { //抛出异常就直接打开设置页面
            startActivity(Intent(Settings.ACTION_SETTINGS))
        }
    }

    //使用此方法弹出对话框提示用户应该需要去设置里面开启权限
    private fun showDialogForStartActivityPermission(intent: Intent, msg: String) {
        AlertDialog.Builder(this@PermissionActivity).setMessage(msg).setCancelable(false)
            .setPositiveButton("去授权") { dialog, _ ->
                startActivity(intent)
                dialog.dismiss()
            }.setNegativeButton("退出") { dialog, _ ->
                dialog.dismiss()
                finish()
            }.show()
    }
}